package com.yang.service.adminimpl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yang.bean.*;
import com.yang.bean.common.BasePageInfo;
import com.yang.bean.common.BaseRespVo;
import com.yang.bean.common.CommonData;
import com.yang.bean.szy.MarketCouponBO;
import com.yang.bean.szy.MarketCouponUpdateBO;
import com.yang.bean.szy.MarketCouponVO;
import com.yang.bean.szyWX.CouponVo;
import com.yang.bean.szyWX.WxcouponExchangeBO;
import com.yang.bean.szyWX.WxcouponReceiveBO;
import com.yang.bean.zdd.vo.IndexVoInWxVo;
import com.yang.bean.zdd.vo.UserOrderVo;
import com.yang.mapper.MarketCartMapper;
import com.yang.mapper.MarketCouponMapper;
import com.yang.mapper.MarketCouponUserMapper;
import com.yang.service.admin.AdminCouponService;
import com.yang.service.wx.WXUserService;
import com.yang.utils.UserUtil;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

@Service
public class AdminCouponServiceImpl implements AdminCouponService {
    @Autowired
    MarketCouponMapper marketCouponMapper;

    @Autowired
    DefaultWebSessionManager defaultWebSessionManager;

    @Autowired
    MarketCouponUserMapper couponUserMapper;

    @Autowired
    MarketCartMapper marketCartMapper;

    @Override
    public BaseRespVo<CommonData<MarketCoupon>> queryAllCoupon(BasePageInfo info, String name, Integer type, Integer status) {
        PageHelper.startPage(info.getPage(), info.getLimit());
        MarketCouponExample example = new MarketCouponExample();
        example.setOrderByClause(info.getSort() + " " + info.getOrder());
        MarketCouponExample.Criteria criteria = example.createCriteria();
        if (name != null && !" ".equals(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        if (type != null && !" ".equals(type)) {
            criteria.andTypeEqualTo(type.shortValue());
        }
        if (status != null && !" ".equals(status)) {
            criteria.andStatusEqualTo(status.shortValue());
        }
        //外层VO
        BaseRespVo<CommonData<MarketCoupon>> commonDataBaseRespVo = new BaseRespVo<CommonData<MarketCoupon>>();

        //内层VO
        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(example);
        commonDataBaseRespVo.setErrno(0);
        //中层VO
        CommonData<MarketCoupon> marketCouponCommonData = new CommonData<>();

        marketCouponCommonData.setList(marketCoupons);
        commonDataBaseRespVo.setData(marketCouponCommonData);
        return commonDataBaseRespVo;
    }


    /**
     * 完成
     *
     * @param marketCouponBO
     * @return
     */
    @Override
    public BaseRespVo<MarketCouponVO> createCoupon(MarketCouponBO marketCouponBO) {
        //Todo 传递进来的值
        MarketCoupon marketCoupon = new MarketCoupon();
        marketCoupon.setName(marketCouponBO.getName());
        marketCoupon.setTotal(marketCouponBO.getTotal());
        int min = marketCouponBO.getMin();
        marketCoupon.setMin(new BigDecimal(min));
        int limit = marketCouponBO.getLimit();
        marketCoupon.setLimit((short) limit);
        int type = marketCouponBO.getType();
        marketCoupon.setType((short) type);
        int status = marketCouponBO.getStatus();
        marketCoupon.setStatus((short) status);
        int goodsType = marketCouponBO.getGoodsType();
        marketCoupon.setGoodsType((short) goodsType);
        int timeType = marketCouponBO.getTimeType();
        marketCoupon.setTimeType((short) timeType);
        marketCoupon.setAddTime(new Date());
        marketCoupon.setUpdateTime(new Date());
        int discount = marketCouponBO.getDiscount();
        marketCoupon.setDiscount(new BigDecimal(discount));
        marketCouponMapper.insertSelective(marketCoupon);
        return BaseRespVo.ok();
    }

    @Override
    public BaseRespVo<MarketCouponUpdateBO> updateCoupon(MarketCouponUpdateBO marketCouponUpdateBO) {

        MarketCoupon marketCoupon = new MarketCoupon();
        marketCoupon.setId(marketCouponUpdateBO.getId());
        marketCoupon.setName(marketCouponUpdateBO.getName());
        marketCoupon.setDesc(marketCouponUpdateBO.getDesc());
        marketCoupon.setTag(marketCouponUpdateBO.getTag());
        String total = marketCouponUpdateBO.getTotal();
        marketCoupon.setTotal(Integer.valueOf(total));
        String min = marketCouponUpdateBO.getMin();
        marketCoupon.setMin(new BigDecimal(min));
        String limit = marketCouponUpdateBO.getLimit();
        marketCoupon.setLimit(Short.parseShort(limit));
        int type = marketCouponUpdateBO.getType();
        marketCoupon.setType((short) type);
        int status = marketCouponUpdateBO.getStatus();
        marketCoupon.setStatus((short) status);
        int goodsType = marketCouponUpdateBO.getGoodsType();
        marketCoupon.setGoodsType((short) goodsType);
        int timeType = marketCouponUpdateBO.getTimeType();
        marketCoupon.setTimeType((short) timeType);
        int days = marketCouponUpdateBO.getDays();
        marketCoupon.setDays((short) days);
        marketCoupon.setAddTime(new Date());
        marketCoupon.setUpdateTime(new Date());
        marketCoupon.setStartTime(new Date());
        marketCoupon.setEndTime(new Date());
        String discount = marketCouponUpdateBO.getDiscount();
        marketCoupon.setDiscount(new BigDecimal(discount));
        marketCouponMapper.updateByPrimaryKeySelective(marketCoupon);
        return BaseRespVo.ok();
    }

    @Override
    public void deleteCoupon(MarketCoupon marketCoupon) {
        int id = marketCoupon.getId();
        marketCouponMapper.deleteByPrimaryKey(id);
    }
    @Override
    public BaseRespVo<CommonData> queryListuser(Integer page, Integer limit, Integer couponId, String sort, String order) {

        return BaseRespVo.ok();
    }
    @Override
    public BaseRespVo<MarketCoupon> queryCoupon(Integer id) {
        MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(id);
        BaseRespVo<MarketCoupon> baseRespVo = new BaseRespVo<>();
        baseRespVo.setData(marketCoupon);
        return baseRespVo;
    }

    @Override
    public void receiveCoupon(WxcouponReceiveBO wxcouponReceiveBO, HttpServletRequest request) {
        MarketUser user = UserUtil.getUserMsg(request, defaultWebSessionManager);
        int id = wxcouponReceiveBO.getCouponId();
        //1:根据userID查询couponId
        MarketCouponUserExample couponUserExample = new MarketCouponUserExample();
        couponUserExample.createCriteria().andUserIdEqualTo(user.getId());
        List<MarketCouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);
        //
        //2.拿到一个用户拥有的所有优惠卷Id
//        List couponIds = new ArrayList();
        HashSet<Integer> set = new HashSet<>();
        for (MarketCouponUser couponUser : couponUsers) {
//            couponIds.add(couponUser.getCouponId());
            set.add(couponUser.getCouponId());
        }
       //TODO 用户所拥有的的id
        // 优惠卷的id
        if (set.size()==0){
            MarketCouponUser marketCouponUser = new MarketCouponUser();
            MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(id);
            marketCouponUser.setUserId(user.getId());
            marketCouponUser.setCouponId(wxcouponReceiveBO.getCouponId());
            marketCouponUser.setStatus(marketCoupon.getStatus());
            marketCouponUser.setStartTime(marketCoupon.getStartTime());
            marketCouponUser.setEndTime(marketCoupon.getEndTime());
            marketCouponUser.setAddTime(marketCoupon.getAddTime());
            marketCouponUser.setUpdateTime(marketCoupon.getUpdateTime());
            marketCouponUser.setDeleted(marketCoupon.getDeleted());
            couponUserMapper.insert(marketCouponUser);
        }
        for (Integer integer : set) {
            if (integer!=id){
                MarketCouponUser marketCouponUser = new MarketCouponUser();
                MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(id);
                marketCouponUser.setUserId(user.getId());
                marketCouponUser.setCouponId(wxcouponReceiveBO.getCouponId());
                marketCouponUser.setStatus(marketCoupon.getStatus());
                marketCouponUser.setStartTime(marketCoupon.getStartTime());
                marketCouponUser.setEndTime(marketCoupon.getEndTime());
                marketCouponUser.setAddTime(marketCoupon.getAddTime());
                marketCouponUser.setUpdateTime(marketCoupon.getUpdateTime());
                marketCouponUser.setDeleted(marketCoupon.getDeleted());
                couponUserMapper.insert(marketCouponUser);
                break;
            }
        }
    }

    @Override
    public CommonData queryAllMyCoupon(BasePageInfo info, Integer status, Integer userId) {
        PageHelper.startPage(info.getPage(), info.getLimit());
        
        //1:根据userID查询couponId
        MarketCouponUserExample couponUserExample = new MarketCouponUserExample();
        couponUserExample.createCriteria().andUserIdEqualTo(userId).andStatusEqualTo(status.shortValue());
        List<MarketCouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);

        //2:再根据couponId查询coupon表，得到一个list
        List<MarketCoupon> list = new ArrayList<>();
        for (MarketCouponUser couponUser : couponUsers) {
            MarketCoupon coupon = marketCouponMapper.selectByPrimaryKey(couponUser.getCouponId());
            list.add(coupon);
        }

        List<CouponVo> couponVoList = new ArrayList<>();
        for (MarketCoupon coupon : list) {
            CouponVo couponVo = new CouponVo();
            couponVo.setAvailable(false);
            couponVo.setCid(coupon.getId());
            couponVo.setDesc(coupon.getDesc());
            couponVo.setDiscount(coupon.getDiscount());
            couponVo.setEndTime(coupon.getEndTime());
            couponVo.setStartTime(coupon.getStartTime());
            couponVo.setId(userId);
            couponVo.setMin(coupon.getMin());
            couponVo.setName(coupon.getName());
            couponVo.setTag(coupon.getTag());
            couponVoList.add(couponVo);
        }

        PageInfo<CouponVo> pageInfo = new PageInfo<>(couponVoList);

        return CommonData.data(pageInfo);

    }

    @Override
    public void exchangeCoupon(WxcouponExchangeBO wxcouponExchangeBO,HttpServletRequest request) {
        MarketUser user = UserUtil.getUserMsg(request, defaultWebSessionManager);
        String code = wxcouponExchangeBO.getCode();
        MarketCoupon marketCoupon = marketCouponMapper.selectByCodeKey(code);
        if (marketCoupon.equals(null)){
           return ;
        }
        MarketCouponUser marketCouponUser = new MarketCouponUser(null,user.getId(),marketCoupon.getId(),marketCoupon.getStatus(),null,marketCoupon.getStartTime(),
                marketCoupon.getEndTime(),null,marketCoupon.getAddTime(),marketCoupon.getUpdateTime(),marketCoupon.getDeleted());
        marketCouponMapper.insertMyCoupons(marketCouponUser);
    }

    @Override

    public CommonData selectListCoupon(Integer cartId, Integer grouponRulesId, Integer userId) {
        //1.根据cartId查询cart表
        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.createCriteria().andUserIdEqualTo(userId).andIdEqualTo(cartId);
        MarketCart marketCart = marketCartMapper.selectByPrimaryKey(cartId);
        //2.得到购物车金额,判断是否满足使用优惠卷条件
        //2.1  查询用户名下所有的优惠卷
        //2.1.1:根据userID查询couponId
        MarketCouponUserExample couponUserExample = new MarketCouponUserExample();
        couponUserExample.createCriteria().andUserIdEqualTo(userId);
        List<MarketCouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);

        //2.1.2:再根据couponId查询coupon表，得到一个list
        List<MarketCoupon> list = new ArrayList<>();
        for (MarketCouponUser couponUser : couponUsers) {
            MarketCouponExample couponExample = new MarketCouponExample();
            couponExample.createCriteria().andMinGreaterThan(marketCart.getPrice()).andIdEqualTo(couponUser.getCouponId());
//            MarketCoupon coupon = marketCouponMapper.selectByPrimaryKey(couponUser.getCouponId());
            List<MarketCoupon> couponList = marketCouponMapper.selectByExample(couponExample);
            for (MarketCoupon coupon : couponList) {
                list.add(coupon);
            }
        }

        List<CouponVo> couponVoList = new ArrayList<>();
        for (MarketCoupon coupon : list) {
            CouponVo couponVo = new CouponVo();
            couponVo.setAvailable(false);
            couponVo.setCid(coupon.getId());
            couponVo.setDesc(coupon.getDesc());
            couponVo.setDiscount(coupon.getDiscount());
            couponVo.setEndTime(coupon.getEndTime());
            couponVo.setStartTime(coupon.getStartTime());
            couponVo.setId(userId);
            couponVo.setMin(coupon.getMin());
            couponVo.setName(coupon.getName());
            couponVo.setTag(coupon.getTag());
            couponVoList.add(couponVo);
        }


        PageInfo<CouponVo> pageInfo = new PageInfo<>(couponVoList);


        return CommonData.data(pageInfo);
    }

    public CommonData<MarketCoupon> couponList(Integer page, Integer limit) {
        PageHelper.startPage(page,limit);
        MarketCouponExample marketCouponExample = new MarketCouponExample();

        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(marketCouponExample);

        PageInfo<MarketCoupon> pageInfo = new PageInfo<>(marketCoupons);

        return CommonData.data(pageInfo);

    }
}


